<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="请输入部门名称或者编号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->

        <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="sn" label="部门编号" width="130" sortable>
            </el-table-column>
            <el-table-column prop="name" label="部门名称" width="130" sortable>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="130" sortable>
                <template scope="scope">
                    <span size="small" style="color: green" v-if="scope.row.state==0">启用</span>
                    <span size="small" style="color: red" v-else-if="scope.row.state==-1">禁用</span>
                    <span size="small" style="color: darkblue" v-else>未知</span>
                </template>
            </el-table-column>
            <el-table-column prop="manager.username" label="管理员" width="130" sortable>
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" width="130" sortable>
            </el-table-column>


            <el-table-column label="操作">
                <template scope="scope">
                    <!--handleEdit:绑定的handleEdit事件，只要点击它就会触发，这个是编辑后回显-->
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>

            <el-pagination layout="prev, pager, next"
                           @current-change="handleCurrentChange"
                           :page-size="pageSize"
                           :total="total"
                           style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->

        <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="部门姓名" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="editForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="editForm.state">
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                        <el-radio class="radio" :label="0">启用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="管理员">
                    <!--<el-input v-model="editForm.manager"></el-input>
                        :key:  唯一标识
                        :label: 展示的数据
                        :value：提交到后台的数据
                    -->

                    <el-select v-model="editForm.manager" placeholder="请选择" value-key="id">
                        <el-option
                                v-for="item in employees"
                                :label="item.username"
                                :value="item">
                            <span style="float: left">{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                        </el-option>
                    </el-select>
                    <!--<el-select clearable v-model="editForm.manager" placeholder="请选择" value-key="id">
                        <el-option
                                v-for="item in employees"
                                :label="item.username"
                                :value="item">
                            <span style="float: left">{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                            &lt;!&ndash;<span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>&ndash;&gt;
                        </el-option>
                    </el-select>-->
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader v-model="editForm.parent"
                                 :options="Trees"
                                 :props="{
								checkStrictly: true,
								label: 'name',
								value: 'id'
							}"
                                 clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>



    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

    export default {
        data() {
            return {
                Trees: [],
                title:"",
                filters: {
                    keyword: ''
                },
                employees:[],
                departments: [],
                total: 0,
                pageSize:5,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列

                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入编号', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: null,
                    name: "",
                    sn: "",
                    state: 0,
                    manager: null,
                    parent: null
                },

            }
        },
        methods: {
            //性别显示转换
            formatSex: function (row, column) {
                return row.state == 0 ? '启用' : row.state == -1 ? '禁用' : '未知';
            },
            handleCurrentChange(currentPage) {
                this.page = currentPage;
                this.getDepartments();
            },
            //获取部门列表
            getDepartments() {
                let para = {
                    currentPage: this.page,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true; // 忙等

                // 发送请求
                this.$http.post("/dept",para)
                    .then(result=>{ // 请求成功了
                        this.listLoading = false; // 忙等

                        this.departments = result.data.list;
                        this.total = result.data.count;
                    }).catch(result=>{
                    alert("系统异常。。。")
                })

                //NProgress.start();
                /*getDepartmentListPage(para).then((res) => {
                    this.total = res.data.total;
                    this.departments = res.data.departments;
                    this.listLoading = false;
                    //NProgress.done();
                });*/
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true; // 忙等框。
                    //NProgress.start();
                    // let para = { id: row.id };

                    this.$http.delete("/dept/"+row.id)
                        .then(result=>{ // jsonResult： success， msg
                            this.listLoading = false; // ，忙等框。
                            if(result.data.success){ // 删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;
                                this.getDepartments();
                            }else{// 删除失败
                                this.$message({
                                    message: result.data.msg,
                                    type: 'error'
                                });
                                this.page = 1;
                                this.getDepartments();
                            }
                        }).catch(result=>{ // 请求失败，
                        alert("系统错误")
                    })

                    /*removeDepartment(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getDepartments();
                    });*/
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.title = "编辑"
                this.editFormVisible = true;
                let editDept =Object.assign({}, row)  // 回显
                /*row表示当前回显的哪一行数据*/
                if(editDept.parent){
                    console.debug(editDept)
                    let d=editDept.dirPath;
                    let arrDirPath=d.split("/");
                    let arr=[];
                    for(let i=1;i<arrDirPath.length-1;i++){
                        arr.push(parseInt(arrDirPath[i])) ;
                    }
                    console.debug(arr)
                    editDept.parent=arr;
                }
                this.editForm =editDept
                this.getEmployees();


            },
            //显示新增界面
            handleAdd: function () {
                this.title = "新增"
                this.getEmployees();
                this.editFormVisible = true;
                this.editForm = {
                    id: null,
                    name: "",
                    sn: "",
                    state: 0,
                    manager: null,
                    parent: null
                };

            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => { // 检验规则
                    if (valid) {
                        this.$confirm('确认提交吗？', "温馨提示", {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            //克隆数据，传到后台的数据
                            let para = Object.assign({}, this.editForm);

                            // 重新编辑请求携带的数据
                            if(para.parent){
                                let arr = para.parent;   //parent: {id:xx,name:xx,sn:xx}
                                let did = arr[arr.length-1];
                                para.parent = {"id":did}
                            }

                            this.$http.put("/dept",para)
                                .then(result=>{
                                    this.editLoading = false;
                                    this.editFormVisible = false;
                                    if(result.data.success){ // 操作成功
                                        this.$message({
                                            message: '操作成功',
                                            type: 'success'
                                        });
                                        this.page = 1;
                                        this.getDepartments();
                                    }else{// 操作失败
                                        this.$message({
                                            message: result.data.msg,
                                            type: 'error'
                                        });
                                        this.page = 1;
                                        this.getDepartments();
                                    }
                                }).catch(result=>{
                                this.editLoading = false;
                                this.editFormVisible = false;
                                alert("系统错误")
                            })

                            /*editDepartment(para).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getDepartments();
                            });*/
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            addDepartment(para).then((res) => {
                                this.addLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getDepartments();
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除 stream
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);// [1,2,4,5]
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true; // 忙等框
                    //NProgress.start();
                    // let para = { ids: ids };

                    this.$http.patch("/dept",ids)
                        .then(result=>{

                            this.listLoading = false; // ，忙等框。
                            if(result.data.success){ // 删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;
                                this.getDepartments();
                            }else{// 删除失败
                                this.$message({
                                    message: result.data.msg,
                                    type: 'error'
                                });
                                this.page = 1;
                                this.getDepartments();
                            }
                        }).catch(result=>{
                        alert("系统错误")
                    })


                    /*batchRemoveDepartment(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getDepartments();
                    });*/
                }).catch(() => {

                });
            },
            // 查询所有的员工
            getEmployees(){
                this.$http.get("/emp")
                    .then(result=>{
                        this.employees = result.data;
                    })
            },
            deptTree(){
                this.$http.get("/dept/tree")
                    .then(result=>{
                        this.Trees = result.data;
                    })
            }
        },
        mounted() {
            this.getDepartments();
            this.getEmployees();
            this.deptTree();
        }
    }

</script>

<style scoped>

</style>
